<template>
  <view class="form-container">
    <!-- 专辑名称 -->
    <view class="input-section">
      <text>专辑名称</text>
      <input v-model="formData.title" placeholder="请输入专辑名称" />
    </view>

    <!-- 分类选择 -->
    <view class="select-section">
      <text>分类</text>
      <picker mode="selector" :range="categoryNames" range-key="name" @change="onCategoryChange">
        <view>{{ selectedCategoryName || '请选择分类' }}</view>
      </picker>
    </view>

    <!-- 专辑描述 -->
    <view class="textarea-section">
      <text>专辑描述</text>
      <textarea v-model="formData.description" placeholder="请输入专辑描述"></textarea>
    </view>

    <!-- 专辑封面上传 -->
    <view class="upload-section">
      <text>专辑封面</text>
      <button @click="chooseImage">选择图片</button>
      <block v-for="(item, index) in formData.fileList" :key="index">
        <image
          style="
            width: 100rpx;
            height: 100rpx;
            object-fit: cover;
            border-radius: 4rpx;
            margin-right: 10rpx;
            margin-bottom: 10rpx;
            cursor: pointer;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
          "
          :src="item.url"
          mode="aspectFill"
          @click="previewImage(index)"
        />
        <text @click="removeImage(index)">删除</text>
      </block>
    </view>

    <!-- 提交按钮 -->
    <view class="button-container">
      <button type="primary" @click="submitForm">提交</button>
      <button @click="resetForm">重置</button>
    </view>
  </view>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import useUserStore from '@/store/modules/user'
import { apiGetCategoryNames, apiPostingAlbum } from '@/api/tsApis'
import { showConfirm, toast } from '@/utils/common'
import { getToken, getUserId, getUserName } from '@/utils/auth'
import { apiGetPostingDetail } from '@/api/apis'
const props = defineProps({
  id: {
    type: String,
    default: '',
  },
})

// 表单数据
const formData = reactive({
  title: '',
  description: '',
  classId: '',
  fileList: [],
})

// 分类选项
const categoryNames = ref([])
const selectedCategoryName = ref('')

// 获取分类名称
onMounted(async () => {
  const pId = Number(props.id)
  try {
    // 判断是否有id，如果有，则为编辑模式，否则为新增模式
    if (!isNaN(pId)) {
      const params = {
        id: pId,
        type: 0,
        userId: getUserId(),
      }
      const res = await apiGetPostingDetail(params)
      formData.title = res.data.title
      formData.description = res.data.description
      formData.classId = res.data.classId
      selectedCategoryName.value = res.data.className
      formData.fileList = [
        {
          name: res.data.imgUrl,
          url: res.data.imgUrl,
        },
      ]
    }
    const res = await apiGetCategoryNames('2')
    categoryNames.value = res.data
  } catch (err) {
    console.error(err)
  }
})

// 分类选择变更处理
const onCategoryChange = (e) => {
  const index = e.detail.value
  formData.classId = categoryNames.value[index].id
  selectedCategoryName.value = categoryNames.value[index].name
}

// 图片上传相关逻辑
const chooseImage = async () => {
  const res = await uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
  })

  if (res.tempFilePaths.length > 0) {
    formData.fileList.push({
      name: res.tempFiles[0].name,
      url: res.tempFilePaths[0],
    })
  }
}

const removeImage = (index) => {
  showConfirm({
    title: '确认删除',
    content: '确认删除该图片吗？',
    success: async () => {
      formData.fileList.splice(index, 1)
    },
  })
}

const previewImage = (index) => {
  uni.previewImage({
    urls: formData.fileList.map((item) => item.url),
    current: formData.fileList[index].url,
  })
}

const submitUpload = () => {
  formData.fileList.forEach((file, index) => {
    uni.uploadFile({
      url: import.meta.env.VITE_APP_ADMIN_URL + '/common/uploadOSS', // 替换为你的上传接口地址
      filePath: file.url,
      name: 'file',
      formData: {
        fileName: file.name,
      },
      header: {
        Authorization: 'Bearer ' + getToken(),
      },
      success: (uploadRes) => {
        const response = JSON.parse(uploadRes.data)
        console.log('response', response)
        if (response.code === 200) {
          formData.fileList[index] = {
            name: response.newFileName,
            url: response.url,
          }
          toast('上传成功')
          // 准备提交的数据
          const albumData = {
            id: Number(props.id) || null,
            imgUrl: formData.fileList[0].url,
            title: formData.title,
            description: formData.description,
            userId: getUserId(),
            nickname: getUserName(),
            classId: formData.classId,
          }

          try {
            apiPostingAlbum(albumData).then((res) => {
              if (res.code === 200) {
                resetForm()
                toast('提交成功')
              }
            })
          } catch (err) {
            toast('提交失败')
            console.error(err)
          }
        } else {
          toast(response.msg)
        }
      },
      fail: (err) => {
        toast('上传失败')
        console.error(err)
      },
    })
  })
}

// 提交表单
const submitForm = async () => {
  if (!formData.title || !formData.classId || formData.fileList.length === 0) {
    toast('请填写完整信息')
    return
  }

  await submitUpload()
}

// 重置表单
const resetForm = () => {
  formData.title = ''
  formData.description = ''
  formData.classId = ''
  formData.fileList = []
}

</script>

<style lang="scss" scoped>
.form-container {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);

  .input-section,
  .select-section,
  .textarea-section,
  .upload-section {
    margin-bottom: 20px;
    padding: 10px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  }

  input,
  textarea {
    width: 100%;
    height: 80rpx;
    padding: 10px;
    box-sizing: border-box;
    border: 1px solid #ddd;
    border-radius: 4px;
    transition: border-color 0.3s;

    &:focus {
      border-color: #007bff;
    }
  }

  textarea {
    height: 200rpx;
    resize: none;
  }

  .button-container {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;

    button {
      flex-grow: 1;
      margin: 0 5px;
      padding: 10px;
      background-color: #007bff;
      color: #fff;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.3s;

      &:hover {
        background-color: #0056b3;
      }
    }
  }

  .upload-section {
    image {
      width: 100rpx;
      height: 100rpx;
      object-fit: cover;
      border-radius: 4rpx;
      margin-right: 10rpx;
      margin-bottom: 10rpx;
      cursor: pointer;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    text {
      color: #ff4d4f;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #d32f2f;
      }
    }
  }
}
</style>
